/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.thienloc.omap.controller.broadcast;

import com.thienloc.omap.controller.BaseBean;
import com.thienloc.omap.entity.Prefix;
import com.thienloc.omap.jdbc.dao.TblSmsBroadcastingDao;
import com.thienloc.omap.jdbc.dao.TblTmpDao;
import com.thienloc.omap.jdbc.entity.TblSmsBroadcasting;
import com.thienloc.omap.service.broadcast.BroadcastService;
import com.thienloc.omap.session.BlackListFacade;
import com.thienloc.omap.session.PrefixFacade;
import com.thienloc.omap.util.CommonUtil;
import com.thienloc.omap.util.Constant;
import com.thienloc.omap.util.JsfUtil;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Serializable;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author GiangLT
 */
@ManagedBean
@ViewScoped
public class BroadcastInstantBean extends BaseBean implements Serializable {

    @EJB
    private PrefixFacade prefixFacade;
    @EJB
    private BlackListFacade blackListFacade;
    private String msisdn;
    private String content;
    private String shortCode;
    private final Logger logger = LoggerFactory.getLogger(BroadcastInstantBean.class);

    public void sendSms() {
        try {
            if (content.contains(";") || content.contains(";")) {
                JsfUtil.addErrorMessage("Sai nội dung", "Nội dung tin nhắn không được chứa dấu ';' hoặc dấu '|'");
                return;
            }
            BroadcastService broadcastService = new BroadcastService();
            broadcastService.connect();

            String prefixStr = CommonUtil.getPrefix(CommonUtil.normalizeMsisdn(msisdn.trim()));
            Prefix prefix = prefixFacade.findByPrefix(prefixStr);

            if (prefix == null) {
                JsfUtil.addErrorMessage("Sai số cần gửi đi", "Số cần gửi đi không thuộc nhà mạng nào");
                return;
            }

            StringBuilder sb = new StringBuilder();
            int seq = sessionBean.getBroadcastInstantSeq();
            sb.append(seq);//????
            sb.append(";");
            sb.append(msisdn);
            sb.append(";");
            sb.append(shortCode);
            sb.append(";");
            sb.append(content);
            sb.append(";");
            sb.append("smsgate_").append(prefix.getOperator());
            sb.append("|");

            broadcastService.send(sb.toString());
            JsfUtil.addSuccessMessage("Thành công!", "Đã gửi tin nhắn tới số " + msisdn);
            broadcastService.disconnect();
        } catch (UnknownHostException ex) {
            logger.error("[{}]: ", getUsername(), ex);
            JsfUtil.addErrorMessage("Lỗi!", "Không tìm thấy module gửi tin");
        } catch (IOException ex) {
            logger.error("[{}]: ", getUsername(), ex);
            JsfUtil.addErrorMessage("Lỗi!", "Lỗi kết nối tới module gửi tin");
        } catch (Exception ex) {
            logger.error("[{}]: ", getUsername(), ex);
            JsfUtil.addErrorMessage("Lỗi!", "Có lỗi xảy ra trong quá trình gửi tin");
        }
    }

    public void sendMultiSms() {
        if (content.contains(";") || content.contains(";")) {
            JsfUtil.addErrorMessage("Sai nội dung", "Nội dung tin nhắn không được chứa dấu ';' hoặc dấu '|'");
            return;
        }
        BroadcastService broadcastService = new BroadcastService();
        

        try {
            String[] mdns = msisdn.split("\\n");
            logger.warn("[{}]: Attempt to send direct sms to {} customers", getUsername(), mdns.length);
                
            Properties properties = new Properties();
            File file = new File(Constant.CONFIG_FOLDER + Constant.CONFIG_FILE_NAME);
            properties.load(new FileReader(file));
            Integer broadcastLimitNum = Integer.valueOf(properties.getProperty("broadcast.limitNum", "5"));
            if (mdns.length > broadcastLimitNum) {
                JsfUtil.addErrorMessage("Vượt số lượng", "Số lượng khách hàng được phép gửi tin ko được quá " + broadcastLimitNum);
                return;
            }

            broadcastService.connect();
            int cnt = 0;
            int total = 0;
            Integer speed = Integer.valueOf(properties.getProperty("broadcast.speed", "9"));

            if (properties.getProperty("broadcast.includeSuffix", "false").equalsIgnoreCase("true")) {
                String suffix = properties.getProperty("broadcast.suffix", "");
                content = content + suffix;
            }

            if (properties.getProperty("broadcast.includePrefix", "false").equalsIgnoreCase("true")) {
                String prefix = properties.getProperty("broadcast.prefix", "");
                content = prefix + content;
            }

            TblSmsBroadcastingDao tblSmsBroadcastingDao = new TblSmsBroadcastingDao();
            TblTmpDao tblTmpDao = new TblTmpDao();

            List<Prefix> prefixes = prefixFacade.findAll();
            for (String mdnString : mdns) {
                String mdnStr = mdnString.replaceAll("\\r", "");
                String prefixStr = CommonUtil.getPrefix(CommonUtil.normalizeMsisdn(mdnStr.trim()));
                Prefix validPrefix = null;
                for (Prefix prefix : prefixes) {
                    if (prefix.getPrefix().equals(prefixStr)) {
                        validPrefix = prefix;
                        break;
                    }
                }

                if (validPrefix != null) {
                    boolean excludeBlackList = properties.getProperty("broadcast.excludeBlackList", "false").equalsIgnoreCase("true");
                    if (!excludeBlackList || blackListFacade.findByMsisdn(mdnStr) == null) {

                        StringBuilder sb = new StringBuilder();
                        int seq = sessionBean.getBroadcastInstantSeq();
                        sb.append(seq);//????
                        sb.append(";");
                        sb.append(mdnStr);
                        sb.append(";");
                        sb.append(shortCode);
                        sb.append(";");

                        sb.append(content);
                        sb.append(";");
                        sb.append("smsgate_").append(validPrefix.getOperator()).append("6771");
                        sb.append("|");

                        broadcastService.send(sb.toString());
                        TblSmsBroadcasting tblSmsBroadcasting = new TblSmsBroadcasting();
                        tblSmsBroadcasting.setSc(shortCode);
                        tblSmsBroadcasting.setMsisdn(mdnStr);
                        tblSmsBroadcasting.setProvider("smsgate_" + validPrefix.getOperator() + "6771");
                        tblSmsBroadcasting.setResult("OK");
                        tblSmsBroadcasting.setSms(content);
                        tblSmsBroadcasting.setSentTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

                        tblSmsBroadcastingDao.add(tblSmsBroadcasting);

                        if (properties.getProperty("broadcast.insertNewDb", "false").equalsIgnoreCase("true")) {
                            tblTmpDao.add(tblSmsBroadcasting);
                        }

                        cnt++;
                        total++;
                        if (cnt >= speed) {
                            cnt = 0;
                            Thread.sleep(1000);
                        }
                    }
                }
            }

            JsfUtil.addSuccessMessage("Thành công!", "Đã gửi tin nhắn tới " + total + " số ");
        } catch (UnknownHostException ex) {
            logger.error("[{}]: ", getUsername(), ex);
            JsfUtil.addErrorMessage("Lỗi!", "Không tìm thấy module gửi tin");
        } catch (IOException ex) {
            logger.error("[{}]: ", getUsername(), ex);
            JsfUtil.addErrorMessage("Lỗi!", "Lỗi kết nối tới module gửi tin");
        } catch (Exception ex) {
            logger.error("[{}]: ", getUsername(), ex);
            JsfUtil.addErrorMessage("Lỗi!", "Có lỗi xảy ra trong quá trình gửi tin");
        } finally {
            try {
                broadcastService.disconnect();
            } catch (IOException ex) {
                logger.error("[{}]: ", getUsername(), ex);
            }
        }
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getMsisdn() {
        return msisdn;
    }

    public void setMsisdn(String msisdn) {
        this.msisdn = msisdn;
    }

    public String getShortCode() {
        return shortCode;
    }

    public void setShortCode(String shortCode) {
        this.shortCode = shortCode;
    }
}
